package com.shujia.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author yangjiming
 * @create 2021-04-07 9:54
 */
public class SumScore {
    //1500100001,1000001,98
    public static class SumScoreMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
        //重写map方法

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            System.out.println("Map");
            //获取一行数据
            String line = value.toString();
            //切分数据
            String[] split = line.split(",");
            String id = split[0];
            int score = Integer.parseInt(split[2]);
            context.write(new Text(id),new IntWritable(score));

        }
    }

    public static class SumScoreReduce extends Reducer<Text,IntWritable,Text,IntWritable>{
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            System.out.println("reduce");
            int sum = 0;//统计学生总分
            for (IntWritable value : values) {
                int i = value.get();
                sum+=i;
            }
            String id = key.toString();
            context.write(new Text(id),new IntWritable(sum));
        }
    }

    public static void main(String[] args) throws Exception{
        Job job = Job.getInstance();
        job.setJobName("SumScore");
        job.setJarByClass(SumScore.class);

        //指定map类
        job.setMapperClass(SumScoreMapper.class);
        //指定map输出k和v的类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        //指定reduce
        job.setReducerClass(SumScoreReduce.class);
        //指定reduce输出k和v的类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        //指定输入路径
        FileInputFormat.addInputPath(job,new Path("/data/score.txt"));
        FileSystem fs = FileSystem.get(new Configuration());
        Path path = new Path("/output");
        //指定输出路径(路径不能已存在),如果已存在删除
        if(fs.exists(path)){
            fs.delete(path,true);
        }
        //指定输出路径(路径不能已存在)
        FileOutputFormat.setOutputPath(job,path);
        //启动
        job.waitForCompletion(true);
        System.out.println("加入任务");
    }
}
